//
//  JobsResultSearchView.swift
//  GreenDeal
//
//  Created by yly on 2024/5/20.
//

import UIKit
import RxSwift
import RxCocoa

class JobsResultSearchView: GreenNaviBarView {
    
    fileprivate lazy var disposeBag = DisposeBag()
    var toDetailVCClosure: ((Int,PVDsListCellOperType?)->Void)?
    var dataObserver: BehaviorRelay<[SearchListModelProtocal]> = BehaviorRelay.init(value: [])
    let tableView = TableView()

    
    private func initBinding(){
        //注册cell
        tableView.register(InstallationListTableViewCell.self, forCellReuseIdentifier: InstallationListTableViewCell.reuseCellIdentifier)
        //设置cell信息，绑定数据源
        dataObserver.bind(to: tableView.rx.items(cellIdentifier: InstallationListTableViewCell.reuseCellIdentifier,cellType: InstallationListTableViewCell.self)){(row, model, cell) in
            if let realModel = model as? InstallationListModel{
                cell.setData(realModel)
            }
            //barcode
            cell.barcodeBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
                self?.toDetailVCClosure?(row, .barcode)
            }).disposed(by: cell.disposeBag)
            //checklist
            cell.checklistBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
                self?.toDetailVCClosure?(row, .checklist)
            }).disposed(by: cell.disposeBag)
            //signature
            cell.signatureBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
                self?.toDetailVCClosure?(row, .signature)
            }).disposed(by: cell.disposeBag)
            
        }.disposed(by: self.disposeBag)
        //选择某一行
        tableView.rx.itemSelected.bind { [weak self] (indexPath) in
            self?.toDetailVCClosure?(indexPath.row,nil)
        }.disposed(by: disposeBag)
        //观察数据变化，刷新数据
        dataObserver.asObservable().subscribe(onNext: {[weak self] (list) in
            self?.tableView.reloadData()
        }).disposed(by: disposeBag)
    }
    
    override func setUpView() {
        self.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(Constant.AllOutMargin)
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.bottom.equalTo(Constant.BottomMargin)
        }
        //
        self.tableView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView.showsVerticalScrollIndicator = false
        //防止上拉加载时数据滚动
        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableView.automaticDimension

        self.initBinding()
    }
}
